package cn.kgc.controller;

import cn.kgc.entities.Goods;
import cn.kgc.pojo.Prop;
import cn.kgc.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @GetMapping("/goods")
    public String getAllGoods(Model model){
        List<Goods> list = goodsService.getAllGoods();
        model.addAttribute("list",list);
        return "goodsList";
    }

    @GetMapping("/goods/{id}")
    public String getGoodsById(@PathVariable("id") Integer id, Model model){
        this.setProp(model);
        Goods goods = goodsService.getGoodsById(id);
        model.addAttribute("goods",goods);
        return "goods";
    }

    @PostMapping("/goods")
    public String addGoods(Goods goods){
        goodsService.addGoods(goods);
        return "redirect:/goods";
    }

    @PutMapping("/goods")
    public String updateGoods(Goods goods){
        goodsService.updateGoods(goods);
        return "redirect:/goods";
    }

    @DeleteMapping("/goods/{id}")
    public String deleteGoodsById(@PathVariable("id") Integer id){
       goodsService.deleteGoodsById(id);
        return "redirect:/goods";
    }

    //跳转到新增页面
    @GetMapping("/goods/view")
    public String toAddUI(Model model){
        setProp(model);
        model.addAttribute("goods",new Goods());
        return "goods";
    }

    public void setProp(Model model){
        List<Prop> pid = new ArrayList<>();
        pid.add(new Prop("0","0"));
        pid.add(new Prop("2","2"));
        pid.add(new Prop("1","-1"));

        model.addAttribute("pid",pid);

    }
}
